import dayjs from 'dayjs'
export const useService = createGlobalState(() => {
  const { VITE_OFFICIAL_DOMAIN, VITE_CASINO_IMG_CLOUD_URL } = getEnv()

  // timeStamp
  const time = ref(dayjs().valueOf())

  const { bool: serviceState, setBool } = useBoolean(false)
  const { userInfo, isLogin, logoAndIcoAndLoading } = storeToRefs(useAppStore())
  const { brandKf } = storeToRefs(useBrandStore())
  const { data: sign } = useRequest(ApiMemberBrandKefuSign, {
    ready: isLogin,
    manual: false,
  })

  const serviceUrl = computed(() => {
    if (!brandKf.value)
      return ''

    const detail = brandKf.value.find((item: any) => +item.state === 1)

    let str = ''
    if (isLogin.value && userInfo.value)
      str = `&username=${userInfo.value.username}&sign=${sign.value}`

    return detail && detail.url
      ? (`${detail.url}&lang=${getCurrentUrlLanguage()}${str}&VITE_OFFICIAL_DOMAIN=${VITE_OFFICIAL_DOMAIN}&LOGO_URL=${`${VITE_CASINO_IMG_CLOUD_URL}/${logoAndIcoAndLoading.value.logo_white}`}&time=${time.value}`)
      : ''
  })

  /**
   * 打开客服
   */
  function openService({ isFootBar = false, needDeal = false }: { isFootBar: boolean; needDeal: boolean }) {
    setBool(true)
    if (!isFootBar) {
      const footbarBtn = document.getElementById('h5-footbar-kefu')
      footbarBtn?.click()

      lockBodyScroll(true)
    }
    else {
      setBool(true)
    }
  }


  /**
   * 关闭客服
   */
  function closeService() {
    setBool(false)
    lockBodyScroll(false)
  }

  return {
    serviceState,
    openService,
    closeService,
  }
})
